//
//  QSAddVisitSecondCell.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/3/30.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSAddVisitSecondCell.h"
#import "QSSelectImageCell.h"
#import <SDAutoLayout.h>

static NSString *defaultCell = @"DefaultCell";
static NSString *selectPhotoCell = @"SelectPhotoCell";
@implementation QSAddVisitSecondCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    [self configSubView];
    [self configCollectinoView];
}
- (void)configSubView{
    self.backgroundColor = [UIColor clearColor];
    self.contentView.layer.cornerRadius = 8;
    self.contentView.layer.masksToBounds = YES;
    self.contentView.backgroundColor = [UIColor QSColorWhiteFFFFFF];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.mas_leading).offset(kRealValue(0));
        make.trailing.equalTo(self.mas_trailing).offset(- kRealValue(0));
        make.top.equalTo(self.mas_top).offset(kRealValue(10));
        make.bottom.equalTo(self.mas_bottom).offset(kRealValue(0));
    }];

    
}

- (void)layoutSubviews{
    self.contentTextView.delegate = self;
    self.contentTextView.placeholder = @"请填写您的走访记录...";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recyclingKeyBoard:) name:@"RECYCLING_KEYBOARD" object:nil];
}
//移出键盘响应
- (void)recyclingKeyBoard:(NSNotificationCenter *)notification{
    [self.contentTextView resignFirstResponder];
}

- (void)configCollectinoView{
    self.itemWH = kRealValue(kScreenWidth - 28 - 20 - 9) / 4;
    self.collectionViewH.constant = self.itemWH;
    UICollectionViewFlowLayout *flowLaout = [[UICollectionViewFlowLayout alloc]init];
    flowLaout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //上下间距
        flowLaout.minimumLineSpacing = 3;
    //左右间距
        flowLaout.minimumInteritemSpacing = 3;
    flowLaout.itemSize = CGSizeMake(_itemWH, _itemWH);
    self.collectionVIew.collectionViewLayout = flowLaout;
    
    [self.collectionVIew registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:defaultCell];
    [self.collectionVIew registerClass:[QSSelectImageCell class] forCellWithReuseIdentifier:selectPhotoCell];

    self.collectionVIew.pagingEnabled = NO;
    self.collectionVIew.showsHorizontalScrollIndicator = NO;
    self.collectionVIew.bounces = NO;
    [self.collectionVIew reloadData];
    self.collectionVIew.delegate = self;
    self.collectionVIew.dataSource = self;
    _collectionVIew.didFinishAutoLayoutBlock = ^(CGRect frame) {
        NSLog(@"%f", frame.size.height);
    };
//    [self setupAutoHeightWithBottomView:self.collectionVIew bottomMargin:10];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.picArr.count == 9) {
        return self.picArr.count;
    }else{
        return _picArr.count + 1;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_picArr.count < 9 && indexPath.item == self.picArr.count) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:defaultCell forIndexPath:indexPath];
        UIImageView *pic = [[UIImageView alloc]initWithFrame:cell.contentView.frame];
        //    [pic sd_setImageWithURL:[NSURL URLWithString:_picArr[indexPath.item]]];
        pic.image = [UIImage imageNamed:@"icon_addimage"];
        pic.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:pic];
        return cell;
    }else{
        QSSelectImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:selectPhotoCell forIndexPath:indexPath];
        [cell.imagev setImage:self.picArr[indexPath.row]];
        cell.deleteButton.hidden = NO;
        cell.deleteButton.tag = indexPath.item;
        [cell.deleteButton addTarget:self action:@selector(deletePhotos:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_picArr.count < 9 && indexPath.item == self.picArr.count)  {
        //小于9 点击到添加
        TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
        [imagePicker setSortAscendingByModificationDate:NO];
        imagePicker.selectedAssets = _assestArray;
        imagePicker.allowPickingVideo = NO;
        [[UIViewController currentViewController] presentViewController:imagePicker animated:YES completion:nil];
    }else{
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_assestArray selectedPhotos:_picArr index:indexPath.row];
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        }];
        [[UIViewController currentViewController] presentViewController:imagePickerVc animated:YES completion:nil];
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(_itemWH, _itemWH);
}

//内边距处理
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    // UIEdgeInsets insets = {top, left, bottom, right};
    return UIEdgeInsetsMake(0, 0, 0, 0);
}


#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    self.picArr = [NSMutableArray arrayWithArray:photos];
    
    self.assestArray = [NSMutableArray arrayWithArray:assets];
    if (_picArr.count >= 0 && _picArr.count <= 3) {
        self.collectionViewH.constant = _itemWH;
    }
    if (_picArr.count >= 4 && _picArr.count <= 7 ) {
        self.collectionViewH.constant = _itemWH *2 + 3;
    }
    if (_picArr.count >= 8) {
        self.collectionViewH.constant = _itemWH *3 + 6;
    }
//    [self setupAutoHeightWithBottomView:self.collectionVIew bottomMargin:20];
    [_collectionVIew reloadData];
    if (photos.count > 0) {
        if (self.addVisitDidClickSelectImages) {
            self.addVisitDidClickSelectImages(_picArr);
        }
    }
//    _isSelectOriginalPhoto = isSelectOriginalPhoto;
}

#pragma mark - UITextViewDelegate
-(void)textViewDidEndEditing:(UITextView *)textView{
    if (textView.text.length> 0) {        
        if (self.addVisitDidRemarkEditFinish) {
            self.addVisitDidRemarkEditFinish(textView.text);
        }
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (text.length == 0) return YES;//允许删除。
    if (textView.text.length >= 180) {
        return NO;
    }else{
        return YES;
    }
}

//删除图片数组的某一张
- (void)deletePhotos:(UIButton *)sender{
    [self.picArr removeObjectAtIndex:sender.tag];
    [self.assestArray removeObjectAtIndex:sender.tag];
    if (self.addVisitDidRemarkEditFinish) {
        self.addVisitDidClickSelectImages(self.picArr);
    }
    [self.collectionVIew reloadData];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    for (UIView *view in self.contentView.subviews) {
        [view endEditing:YES];
    }
    [self.collectionVIew endEditing:YES];
    [self endEditing:YES];
}

- (void)setModel:(QSVisitDetailModel *)model{
    _model = model;
//    [self setupAutoHeightWithBottomView:self.collectionVIew bottomMargin:20];
//    [self.collectionVIew reloadData];
}

- (void)dealloc{
    //移除通知
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}
@end
